import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import * as mongoose from 'mongoose';
import { TestVarStatusEnum } from '../../../constants/business.enum';

export type VarTestDocument = VarTest & Document;

//子文档格式
@Schema()
export class VarDocumentType extends Document {
  @Prop({ type: String })
  fileName: string;

  @Prop({ type: String })
  filePath: string;
}

@Schema({
  timestamps: {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
  },
})
export class VarTest extends Document {
  // 字符串变量
  @Prop({ required: true, type: String })
  varString: string;

  // 布尔变量
  @Prop({ type: Boolean, default: false })
  varBool: Boolean;

  // 数值变量
  @Prop({ type: Number, default: 0 })
  varNumber: number;

  // 字符串数组
  @Prop({ type: [String], default: [] })
  varStringArray: string[];

  // 数值数组
  @Prop({ type: [Number], default: [] })
  varNumberArray: number[];

  //枚举
  @Prop({
    type: String,
    enum: TestVarStatusEnum,
    default: TestVarStatusEnum.NORMAL,
  })
  varEnumStatus: string;

  // date 日期
  @Prop({ type: Date, default: new Date() })
  varDate: Date;

  @Prop({ type: Object })
  varObject: object;

  @Prop({ type: [Object] })
  varObjectArray: object[];

  //子文档
  @Prop({ type: () => VarDocumentType })
  varSubDocument: VarDocumentType;

  @Prop({ type: () => [VarDocumentType], default: [] })
  varDocumentArray: VarDocumentType[];

  // 对象字段
  @Prop({
    type: {
      name: String,
      value: Number,
    },
    _id: false, // 不生成子文档的_id
  })
  varObjectHasType: {
    name: string;
    value: number;
  };

  // 嵌套对象数组
  @Prop({
    type: [
      {
        itemName: String,
        itemValue: Number,
      },
    ],
    default: [],
  })
  varObjectArrayHasType: Array<{
    itemName: string;
    itemValue: number;
  }>;

  //关联id - 转入自动转化
  @Prop({
    type: Types.ObjectId,
    set(val) {
      if (val) {
        return new mongoose.Types.ObjectId(val);
      } else {
        return val;
      }
    },
  })
  varObjectId: Types.ObjectId;

  //关联id - 必须穿对应格式的
  @Prop({ type: Types.ObjectId })
  varObjectIdOrigin: Types.ObjectId;
}

export const VarTestSchema = SchemaFactory.createForClass(VarTest);
